package com.trs.zk.common.mybatis.mapper;


import com.trs.zk.common.entity.BaseEntity;
import com.trs.zk.common.lang.StringUtils;
import com.trs.zk.common.mybatis.annotation.Column;
import com.trs.zk.common.mybatis.annotation.JoinTable;
import com.trs.zk.common.mybatis.annotation.Table;

import java.util.List;

/**
 * @author msy
 * @date 2018/8/14 18:19
 */
public class MapperHelper {
    public MapperHelper() {}

    /**
     * 获取实体类的物理表
     * @param entityClass
     * @return
     */
    public static Table getTable(Class<?> entityClass) {
        Table table = entityClass.getAnnotation(Table.class);
        if (table == null) {
            throw new MapperException((new StringBuilder()).insert(0,"实体类").append(entityClass).
                    append("的物理表的关联表未设置").toString());
        } else {
            return table;
        }

    }

    public static Table getTable(BaseEntity<?> entity) {
        return getTable(entity.getClass());
    }

    /**
     *
     * @param table
     * @param columns
     * @param attrName
     * @return
     */
    public static List<Column> getColumns(Object table, List<Column> columns, String attrName) {
        Column[] columnArr = null;
        if (table instanceof Table) {
            columnArr = ((Table) table).columns();
        } else {
            if (table instanceof JoinTable) {
                columnArr = ((JoinTable)table).columns();
            }
        }

        if (columnArr != null) {
            int len = columnArr.length;
            for (int i = 0; i < len; i++) {
                Column column = columnArr[i];
                if (column.includeEntity() != Class.class) {
                    getColumns((Table)column.includeEntity().getAnnotation(Table.class), columns, column.attrName());
                } else {
                    columns.add(column);
                }
            }
        }

        return columns;
    }

    public static List<Column> getColumns(Object table, List<Column> columns) {
        return getColumns(table, columns, (String)null);
    }

    public static String getAttrName(Column c) {
        return (String) StringUtils.defaultIfBlank(c.attrName(), StringUtils.camelCase(c.name()));
    }

}
